import numpy as np
import cv2
import time
from util.singleton import Singleton
from concurrent.futures import ThreadPoolExecutor, as_completed


@Singleton
class Parper:
    def __init__(self):
        pass

    executor = ThreadPoolExecutor(4)

    def run(self, obj, height: int = 32, width: int = 32, use_geay: bool = False):
        res = []
        count = 0
        for imgName in obj:
            count += 1
            if count % 1000 == 0:
                print(imgName)
            if use_geay:
                img = cv2.imread(imgName, 0)
            else:
                img = cv2.imread(imgName)
            # 图像缩放
            img = cv2.resize(img, [height, width])
            res.append(img)
        return res, obj[0]

    def getData(self, height: int = 32, width: int = 32, use_geay: bool = False):
        h = ["Harmful/Harmful/harmful" + str(i) + ".jpg" for i in range(1, 16001)]
        k = ["Kitchen/Kitchen/Kitchen" + str(i) + ".jpg" for i in range(1, 16001)]
        o = ["Other/Other/Other" + str(i) + ".jpg" for i in range(1, 16001)]
        r = ["Recyclable/Recyclable/Recyclable" + str(i) + ".jpg" for i in range(1, 16001)]
        resliat = []
        for data, o in self.executor.map(self.run, [h, k, o, r], [height]*4, [width]*4):
            print(o)
            resliat += data
        r = np.array(resliat)
        if use_geay:
            np.save("data/data" + str(height) + "gray.npy", r)
        else:
            np.save("data/data" + str(height) + ".npy", r)


parper = Parper()
# test
if __name__ == "__main__":
    start = time.time()

    # p.getData(False,512,512)
    parper.getData(96, 96)

    # p.getData32()
    end = time.time()
    print(end - start)
